package com.sky.base.security.service;

import com.sky.base.constant.DataStatus;
import com.sky.base.constant.ErrorCode;
import com.sky.base.security.AuthenticationContextHolder;
import com.sky.base.security.pojo.LoginUser;
import com.sky.base.security.utils.TokenUtil;
import com.sky.exception.BaseException;
import com.sky.model.SysLoginLog;
import com.sky.service.SysLoginLogService;
import com.sky.utils.IpUtils;
import com.sky.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDateTime;


/**
 * @author 尹稳健~
 * @version 1.0
 * @time 2022/8/9
 */
@Service
@Slf4j
public class SysLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private SysLoginLogService sysLoginLogService;

    @Autowired
    private TokenUtil tokenUtil;

    public String login(String username,String password){
        // Todo 判断验证码

        Authentication authenticate = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            // 异常处理
            if (e instanceof BadCredentialsException){
                throw new BaseException(ErrorCode.ACCOUNT_PASSWORD_ERROR,"登录密码错误!");
            }else {
                throw new BaseException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        // 记录到日志中登录成功
        Assert.isTrue(sysLoginLogService.save(recordLoginInfo(loginUser)),"日志添加失败");
        // 生成Token,将token存入redis中
        return tokenUtil.createToken(loginUser);
    }

    // 记录日志
    public SysLoginLog recordLoginInfo(LoginUser loginUser){
        SysLoginLog sysLoginLog = new SysLoginLog();
        sysLoginLog.setLoginTime(LocalDateTime.now());
        sysLoginLog.setUsername(loginUser.getUser().getUsername());
        sysLoginLog.setCreateId(loginUser.getUser().getId());
        sysLoginLog.setStatus(DataStatus.NORMAL);
        sysLoginLog.setIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        return sysLoginLog;
    }
}
